<template>
  <div class="profile-container">
    <h2 class="profile-title">个人信息中心</h2>
    <el-card class="profile-card" shadow="hover">
      <div class="profile-header">
        <div class="avatar-container">
          <el-avatar :size="120" :src="userInfo.avatar" class="profile-avatar" />
          <el-tooltip content="点击更换头像" placement="top">
            <el-button
                type="primary"
                size="small"
                circle
                class="avatar-edit-btn"
                @click="triggerAvatarUpload"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
        <div class="profile-basic">
          <h3>{{ userInfo.username }}</h3>
          <el-tag :type="userInfo.gender === '男' ? 'primary' : userInfo.gender === '女' ? 'danger' : 'info'">
            {{ userInfo.gender }}
          </el-tag>
          <el-tag :type="userInfo.gender === '男' ? 'primary' : userInfo.gender === '女' ? 'danger' : 'info'">
            {{ userInfo.age }} 岁
          </el-tag>
        </div>
      </div>

      <el-divider>
        <el-icon><User /></el-icon>
      </el-divider>

      <div class="profile-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="真实姓名">
            <span>{{ userInfo.realName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            <span>{{ userInfo.phone }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            <span>{{ userInfo.email }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            <span>{{ userInfo.idCard }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="生日">
            <span>{{ formatDate(userInfo.birthday) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="profile-actions">
        <el-button type="primary" size="large" @click="showEditDialog" round>
          <el-icon><Edit /></el-icon> 编辑个人信息
        </el-button>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        :title="`编辑个人信息 - ${userInfo.username}`"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="editForm"
          label-width="100px"
          label-position="left"
          :rules="formRules"
          ref="editFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" maxlength="11" show-word-limit placeholder="11位手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" type="email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                  v-model="editForm.birthday"
                  type="date"
                  placeholder="选择生日"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" placeholder="请输入身份证号码" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload-container">
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="uploadHeaders"
                ref="avatarUploader"
            >
              <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="el-upload__tip">点击上传新头像，支持 JPG/PNG 格式，大小不超过 2MB</div>
          </div>
        </el-form-item>

        <!-- 密码修改部分 -->
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="修改密码" name="password">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                  v-model="editForm.oldPassword"
                  type="password"
                  show-password
                  placeholder="请输入当前密码"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="password">
              <el-input
                  v-model="editForm.password"
                  type="password"
                  show-password
                  placeholder="请输入新密码"
              />
              <div class="password-strength">
                <el-progress
                    :percentage="passwordStrength"
                    :format="passwordStrengthFormat"
                    :color="passwordStrengthColor"
                    :stroke-width="6"
                    :show-text="false"
                />
                <span class="strength-text">{{ passwordStrengthText }}</span>
              </div>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                  v-model="editForm.confirmPassword"
                  type="password"
                  show-password
                  placeholder="请再次输入新密码"
              />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false" size="large">取消</el-button>
          <el-button
              type="primary"
              @click="submitEdit"
              size="large"
              :loading="loading"
          >
            保存更改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, nextTick} from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios";
import { Plus, Edit, User } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';

const router = useRouter();


// 上传URL
const uploadUrl = computed(() => `${BASE_URL}/v1/upload`);

// 组件状态
const loading = ref(false);
const editDialogVisible = ref(false);
const activeCollapse = ref([]); // 控制折叠面板的展开项

// 用户信息
const userInfo = ref({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  gender: '',
  avatar: '',
  idCard: '',
  birthday: '',
  age: 0
});

// 编辑表单
const editForm = ref({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  gender: '',
  avatar: '',
  idCard: '',
  birthday: '',
  oldPassword: '',
  password: '',
  confirmPassword: ''
});

// 表单引用
const editFormRef = ref();
const avatarUploader = ref();

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  birthday: [
    { required: true, message: '请选择生日', trigger: 'change' }
  ],
  oldPassword: [
    { validator: validateOldPassword, trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 密码强度计算
const passwordStrength = computed(() => {
  if (!editForm.value.password) return 0;

  let strength = 0;
  const password = editForm.value.password;

  // 长度评分
  if (password.length >= 8) strength += 25;
  if (password.length >= 12) strength += 25;

  // 复杂度评分
  if (/[a-z]/.test(password)) strength += 10;
  if (/[A-Z]/.test(password)) strength += 10;
  if (/\d/.test(password)) strength += 10;
  if (/[^a-zA-Z0-9]/.test(password)) strength += 20;

  return Math.min(strength, 100);
});

const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value;
  if (strength < 30) return '弱';
  if (strength < 70) return '中等';
  return '强';
});

const passwordStrengthColor = computed(() => {
  const strength = passwordStrength.value;
  if (strength < 30) return '#f56c6c';
  if (strength < 70) return '#e6a23c';
  return '#67c23a';
});

function passwordStrengthFormat() {
  return '';
}

function validateOldPassword(rule, value, callback) {
  // 如果没有输入新密码，则不验证旧密码
  if (!editForm.value.password && !editForm.value.confirmPassword) {
    callback();
    return;
  }

  if (!value) {
    callback(new Error('请输入当前密码'));
  } else {
    callback();
  }
}

function validatePassword(rule, value, callback) {
  // 如果没有输入新密码，则不验证
  if (!value && !editForm.value.confirmPassword) {
    callback();
    return;
  }

  if (!value) {
    callback(new Error('请输入新密码'));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度在6到20个字符'));
  } else if (value === editForm.value.oldPassword) {
    callback(new Error('新密码不能与旧密码相同'));
  } else {
    callback();
  }
}

function validateConfirmPassword(rule, value, callback) {
  // 如果没有输入确认密码，则不验证
  if (!value && !editForm.value.password) {
    callback();
    return;
  }

  if (!value) {
    callback(new Error('请再次输入新密码'));
  } else if (value !== editForm.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

// 上传请求头
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token');
  return {
    Authorization: `Bearer ${token}`
  };
});

// 格式化日期
function formatDate(date) {
  if (!date) return '未设置';
  return dayjs(date).format('YYYY年MM月DD日');
}

// 计算年龄
function calculateAge(birthday) {
  if (!birthday) return 0;
  const birthDate = new Date(birthday);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

// 显示编辑对话框
function showEditDialog() {
  editForm.value = {
    ...JSON.parse(JSON.stringify(userInfo.value)),
    oldPassword: '',
    password: '',
    confirmPassword: ''
  };
  activeCollapse.value = []; // 默认折叠密码修改部分
  editDialogVisible.value = true;
};

// 触发头像上传
function triggerAvatarUpload() {
  showEditDialog();
  // 等待对话框打开后触发上传
  setTimeout(() => {
    avatarUploader.value.$el.querySelector('.el-upload').click();
  }, 300);
}

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  if (response.state === 2000) {
    editForm.value.avatar = response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
    return false;
  }

  return true;
};

// 提交编辑
async function submitEdit() {
  try {
    await editFormRef.value.validate();

    // 转换性别值：中文 -> 英文
    const genderMap = { '男': 'male', '女': 'female', '其他': 'other' };
    const payload = {
      ...editForm.value,
      gender: genderMap[editForm.value.gender] || editForm.value.gender
    };

    // 确保生日格式正确
    if (payload.birthday) {
      payload.birthday = dayjs(payload.birthday).format('YYYY-MM-DD');
    }

    // 如果没有输入密码相关字段，则移除这些字段
    if (!editForm.value.oldPassword && !editForm.value.password && !editForm.value.confirmPassword) {
      delete payload.oldPassword;
      delete payload.password;
      delete payload.confirmPassword;
    }

    loading.value = true;
    const response = await axios.post(`${BASE_URL}/v1/user/updateOwn`, payload, {
      withCredentials: true
    });

    if (response.data.state === 2000) {
      ElMessage.success('个人信息更新成功');
      editDialogVisible.value = false;

      // 更新本地用户信息
      const updatedUserInfo = {
        ...userInfo.value,
        ...editForm.value,
        // 确保不更新密码字段到本地存储
        oldPassword: '',
        password: '',
        confirmPassword: ''
      };

      // 重新计算年龄
      updatedUserInfo.age = calculateAge(updatedUserInfo.birthday);

      // 更新本地存储
      userInfo.value = updatedUserInfo;
      localStorage.setItem('user', JSON.stringify(userInfo.value));

      // 如果修改了密码，需要重新登录
      if (editForm.value.password) {
        ElMessage.success('密码修改成功，请重新登录');
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        router.push('/login');
      }
    } else {
      ElMessage.error(response.data.message || '更新失败');
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.response?.data?.message || '更新失败');
    }
  } finally {
    loading.value = false;
  }
}

// 获取用户信息
async function fetchUserInfo() {
  try {
    loading.value = true;
    const response = await axios.get(`${BASE_URL}/v1/user/info`, {
      withCredentials: true
    });

    if (response.data?.state === 2000) {
      // 转换性别值：英文 -> 中文
      const genderMap = { 'male': '男', 'female': '女', 'other': '其他' };
      const userData = response.data.data;

      // 确保生日字段存在且格式正确
      if (userData.birthday) {
        userData.birthday = dayjs(userData.birthday).format('YYYY-MM-DD');
      }

      userInfo.value = {
        ...userData,
        gender: genderMap[userData.gender] || userData.gender,
        age: calculateAge(userData.birthday)
      };

      localStorage.setItem('user', JSON.stringify(userInfo.value));
    }
  } catch (error) {
    console.error("获取用户信息出错:", error);
    if (error.response?.status === 401) {
      ElMessage.warning('请重新登录');
      localStorage.removeItem('user');
      router.push('/login');
    } else {
      ElMessage.error(error.response?.data?.message || "获取用户信息失败");
    }
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  // 先从本地存储加载
  const localUser = localStorage.getItem('user');
  if (localUser) {
    try {
      const parsedUser = JSON.parse(localUser);
      // 确保生日字段格式正确
      if (parsedUser.birthday) {
        parsedUser.birthday = dayjs(parsedUser.birthday).format('YYYY-MM-DD');
      }
      userInfo.value = {
        ...parsedUser,
        age: calculateAge(parsedUser.birthday)
      };
    } catch (e) {
      console.error("解析本地用户信息失败:", e);
    }
  }

  // 然后请求最新数据
  fetchUserInfo();
});
</script>

<style scoped>
/* 样式保持不变，与之前相同 */
.profile-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.profile-title {
  text-align: center;
  color: var(--el-color-primary);
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 500;
}

.profile-card {
  margin-top: 20px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.profile-card:hover {
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-container {
  position: relative;
  margin-right: 40px;
}

.avatar-edit-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  transform: translate(30%, 30%);
}

.profile-basic h3 {
  margin: 0 0 15px 0;
  font-size: 26px;
  font-weight: 500;
}

.profile-basic .el-tag {
  margin-right: 10px;
  font-size: 14px;
}

.profile-details {
  margin: 30px 0;
}

.profile-actions {
  margin-top: 40px;
  text-align: center;
}

.profile-actions .el-button {
  margin: 0 15px;
  padding: 12px 25px;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 120px;
  height: 120px;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.el-upload__tip {
  margin-top: 10px;
  color: #999;
  font-size: 12px;
  text-align: center;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.password-strength .el-progress {
  flex: 1;
  margin-right: 10px;
}

.password-strength .strength-text {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  min-width: 30px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
  }

  .avatar-container {
    margin-right: 0;
    margin-bottom: 20px;
  }

  .profile-actions .el-button {
    margin: 5px;
    width: 100%;
  }
}
</style>